﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Gameplay.CharacterFramework
{
    public class RockController:CharacterController
    {

        [SerializeField] private Transform[] _patrolPositions;
        [SerializeField] private float _patrolDistance;
        [SerializeField] private float _attackDistance;
        [SerializeField] private float _attackInterval;
        private float _timer;

        private Transform playerTransform;

        private Role _owner;
        private Role _target;

        private int _patrolIndex;

        private void Awake()
        {
     
            
        }

        private void Start()
        {
            
            _owner = GetComponent<Role>();
            playerTransform = GameObject.FindObjectOfType<PlayerController>().transform;
            _target = playerTransform.GetComponent<Role>();
            _patrolIndex = 0;
            _timer = _attackInterval;
        }

        private void Update()
        {

            if (_owner.Status.IsDamage && _owner.Status.IsDead) 
            {
                return;
            }

            if (RockController.DistanceWithTarget(transform.position, playerTransform.position) >= _patrolDistance || _target.Status.IsDead)
            {
                if (_owner.MoveToTarget(_patrolPositions[_patrolIndex].position))
                {
                    _patrolIndex++;
                    if (_patrolIndex > _patrolPositions.Length - 1)
                    {
                        _patrolIndex = 0;
                    }
                }
            }
            else if (RockController.DistanceWithTarget(transform.position, playerTransform.position) > _attackDistance)
            {
                _owner.MoveToTarget(playerTransform.position);
            }
            else if (RockController.DistanceWithTarget(transform.position, playerTransform.position) <= _attackDistance && !_target.Status.IsDead)
            {
                _owner.Static();
                _timer -= Time.deltaTime;
                if (_timer <= 0)
                {

                    _owner.UseSkill(10000, 1004,_target);
                    _timer = _attackInterval;
                }

            }

        }

        private static float DistanceWithTarget(Vector3 currentPos, Vector3 targetPos)
        {
            return Vector3.Distance(new Vector3(currentPos.x, 0, currentPos.z), new Vector3(targetPos.x, 0, targetPos.z));
        }
    }
}

